﻿//===============================================================================
// PostSharp Poco implementation for EntityFramework
//===============================================================================
// Copyright © Ruurd Boeke.  All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PostSharp.Laos;
using System.Data.Objects.DataClasses;
using System.Data;

namespace EntityFrameworkContrib.PostSharp4EF
{
    /// <summary>
    /// will add calls to the report property changing and propertychanged eventhandlers
    /// This is the implementation for normal entity properties
    /// </summary>
    [Serializable]
    class OnEntityPropertySetChangeTrackSubAspect : OnMethodBoundaryAspect
    {
        private readonly string propertyName;

        public OnEntityPropertySetChangeTrackSubAspect(string propertyName, int AspectPriority)
        {
            this.propertyName = propertyName;
            this.AspectPriority = AspectPriority;
        }

        public override void OnEntry(MethodExecutionEventArgs eventArgs)
        {
            // Get the implementation of INotifyPropertyChanged. We have access to it through the IComposed interface,
            // which is implemented at compile time.
            PocoEntityImplementation implementation =
                (PocoEntityImplementation)
                ((IComposed<IPocoFacade>)eventArgs.Instance).GetImplementation(
                    eventArgs.InstanceCredentials);

            // Raises the PropertyChanged event.
            implementation.ReportPropertyChanging(this.propertyName);
        }

        public override void OnSuccess(MethodExecutionEventArgs eventArgs)
        {
            // Get the implementation of INotifyPropertyChanged. We have access to it through the IComposed interface,
            // which is implemented at compile time.
            PocoEntityImplementation implementation =
                (PocoEntityImplementation)
                ((IComposed<IPocoFacade>)eventArgs.Instance).GetImplementation(
                    eventArgs.InstanceCredentials);

            // Raises the PropertyChanged event.
            implementation.ReportPropertyChanged(this.propertyName);
        }

    }
}
